<template>
  <div class="main">
    <MyHeader :searchForm="searchForm" @search="handleSearch"></MyHeader>
    <el-card class="bottom">
      <div class="table-overview">
        <div class="left">
          <span>社团列表</span>
          <span class="total"
            >共
            <span>{{ pagination.total }}</span>
            条记录
          </span>

          <el-button
            class="delete-btn"
            type="danger"
            v-if="computedSelectedTable.length >= 2"
            @click="handleDeleteList"
            >删除{{ computedSelectedTable.length }}条</el-button
          >
        </div>
        <div class="right">
          <el-button type="primary" @click="exportSelected">导出选中</el-button>
          <el-button type="primary" @click="showExportAllDialog"
            >导出全部</el-button
          >

          <el-button type="primary" @click="showAddDialog">新增</el-button>
        </div>
      </div>

      <OrganizationTable
        :tableData="tableData"
        :selectedTable="selectedTable"
        :pagination="pagination"
        @edit="showEditDialog"
        @delete="showDeleteDialog"
        @selectionChange="handleSelectionChange"
        @currentChange="handleCurrentChange"
        @updateCell="handleUpdateCell"
      >
      </OrganizationTable>

      <AddDialog
        :addDialogVisible="addDialogVisible"
        :form="addForm"
        @closeAddDialog="handleCloseAddDialog"
        @confirm="handleConfirmAdd"
      ></AddDialog>

      <EditDialog
        :editForm="editForm"
        :editDialogVisible="editDialogVisible"
        @closeEditDialog="handleCloseEditDialog"
        @update="handleUpdate"
      >
      </EditDialog>

      <DeleteDialog
        :deleteDialogVisible="deleteDialogVisible"
        @closeDeleteDialog="handleCloseDeleteDialog"
        @confirm="handleDelete"
      >
        确认删除这行数据吗？
      </DeleteDialog>

      <ExportDialog
        :exportAllDialogVisible="exportAllDialogVisible"
        :tableData="exportTableData"
        @closeExportAllDialog="handleCloseExportAllDialog"
      ></ExportDialog>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { utils, writeFile } from "xlsx";

import MyHeader from "./components/MyHeader.vue";
import OrganizationTable from "./components/OrganizationTable.vue";
import AddDialog from "./components/AddDialog.vue";
import EditDialog from "./components/EditDialog.vue";
import DeleteDialog from "@/components/DeleteDialog.vue";
import ExportDialog from "./components/ExportDialog.vue";

import { computed, reactive, toRefs } from "vue";
import lodash from "lodash";
import { ElMessage } from "element-plus";

import { formatDate } from "@/utils/formatDate";

import {
  getList,
  getAll,
  addCommittee,
  editOrganization,
  deleteOrganization,
  deleteOrganizationByList,
} from "@/api/organizationManage/index.ts";
import { useStore } from "vuex";

let tableData: IOrganizationTable[] = reactive([]);

const state = reactive({
  addDialogVisible: false,
  editDialogVisible: false,
  deleteDialogVisible: false,
  exportAllDialogVisible: false,
  editForm: {},
});

const {
  addDialogVisible,
  editDialogVisible,
  deleteDialogVisible,
  exportAllDialogVisible,
  editForm,
} = { ...toRefs(state) };

// 分页功能
const pagination = reactive({
  // 当前页
  currentPage: 1,

  // 一页数据条数
  pageSize: 10,

  // 总数据条数
  total: 0,
});

const handleCurrentChange = (page: number) => {
  getDataList(page, pagination.pageSize, searchForm.organizationName);
};

const store = useStore();

async function getDataList(page: number, limit: number, condition?: string) {
  const { data } = await getList({
    page,
    limit,
    condition,
  });

  if (data.code === 200) {
    pagination.total = data.data.total;

    // 清空数组
    tableData.splice(0, tableData.length);

    for (const item of data.data.records) {
      tableData.push({
        rowId: item._id,
        organizationName: item.name,
        organizationProfile: item.profile,
        organizationMemberCount: item.count,
        organizationPrincipal: item.principal,
        organizationCreateTime: formatDate(new Date(item.createTime)),
      });
    }

    // console.log(tableData);
  }
}

function initTableData() {
  getDataList(pagination.currentPage, pagination.pageSize);
}

initTableData();

// 事件

// 查询功能
const searchForm: IObj = reactive({
  organizationName: "",
});

const handleSearch = () => {
  getDataList(
    pagination.currentPage,
    pagination.pageSize,
    searchForm.organizationName
  );
};

// 添加社团功能
const addForm = reactive({
  organizationName: "",
  organizationProfile: "",
  organizationMemberCount: 0,
  organizationPrincipal: "",
  organizationCreateTime: new Date(),
});
const showAddDialog = () => {
  addDialogVisible.value = true;
};

const handleCloseAddDialog = () => {
  addDialogVisible.value = false;
};

const handleConfirmAdd = async () => {
  const { data } = await addCommittee({
    name: addForm.organizationName,
    principal: addForm.organizationPrincipal,
    createTime: addForm.organizationCreateTime,
    profile: addForm.organizationProfile,
  });

  if (data.code === 200) {
    initTableData();

    handleCloseAddDialog();

    ElMessage({
      message: "新增成功",
      type: "success",
    });

    // addForm.organizationName = '';
    // addForm.organizationPrincipal = '';
    // addForm.organizationCreateTime = new Date();
    // addForm.organizationProfile = '';
  }
};
// 添加功能结束

// 编辑功能
const showEditDialog = (row: IOrganizationTable) => {
  editDialogVisible.value = true;
  editForm.value = lodash.cloneDeep(row);

  (editForm.value as any).organizationCreateTime = new Date(
    (editForm.value as IOrganizationTable).organizationCreateTime
  );
};

const handleCloseEditDialog = () => {
  editDialogVisible.value = false;
};

const handleUpdate = async () => {
  const { data } = await editOrganization({
    _id: (editForm.value as IOrganizationTable).rowId,
    name: (editForm.value as IOrganizationTable).organizationName,
    principal: (editForm.value as IOrganizationTable).organizationPrincipal,
    profile: (editForm.value as IOrganizationTable).organizationProfile,
    createTime: (editForm.value as IOrganizationTable).organizationCreateTime,
  });

  if (data.code === 200) {
    handleCloseEditDialog();
    initTableData();

    ElMessage({
      message: "更新成功",
      type: "success",
    });
  }
};

const handleUpdateCell = async (index: number, attribute: string) => {
  const { data } = await editOrganization({
    _id: tableData[index].rowId,
    name: tableData[index].organizationName,
    principal: tableData[index].organizationPrincipal,
    profile: tableData[index].organizationProfile,
    createTime: tableData[index].organizationCreateTime,
  });

  if (data.code === 200) {
    initTableData();

    ElMessage({
      message: "更新成功",
      type: "success",
    });
  }
};

// 编辑功能结束

// 删除功能
let deleteId: number;
const showDeleteDialog = (row: IOrganizationTable) => {
  deleteId = row.rowId;
  deleteDialogVisible.value = true;
};

const handleCloseDeleteDialog = () => {
  deleteDialogVisible.value = false;
};

const handleDelete = async () => {
  const { data } = await deleteOrganization(deleteId);

  if (data.code === 200) {
    handleCloseDeleteDialog();

    if (selectedTable[pagination.currentPage] !== undefined) {
      selectedTable[pagination.currentPage] = selectedTable[
        pagination.currentPage
      ].filter((item: IObj) => item.rowId != deleteId);
    }

    const organizationMap = store.getters.organizationMap;
    Reflect.deleteProperty(organizationMap, deleteId.toString());

    store.dispatch("initOrganizationMap", organizationMap);

    initTableData();

    ElMessage({
      message: "删除成功",
      type: "success",
    });
  }
};

const handleDeleteList = async () => {
  const idList = [];

  for (const item of computedSelectedTable.value) {
    idList.push(item.rowId);
  }

  console.log(idList);

  const { data } = await deleteOrganizationByList(idList);

  if (data.code === 200) {
    ElMessage({
      message: "删除成功",
      type: "success",
    });

    const organizationMap = store.getters.organizationMap;

    for (const deleteId of idList) {
      const page = Math.ceil(pagination.total / pagination.pageSize);

      for (let i = 1; i <= page; i++)
        if (selectedTable[i] !== undefined) {
          selectedTable[i] = selectedTable[i].filter(
            (item: IObj) => item.rowId != deleteId
          );
        }

      Reflect.deleteProperty(organizationMap, deleteId.toString());
    }

    store.dispatch("initOrganizationMap", organizationMap);

    initTableData();
  }
};

// 删除功能结束

// 导出功能

const exportTableData: IObj[] = reactive([]);

const showExportAllDialog = async () => {
  const { data: res } = await getAll();

  if (res.code === 200) {
    // 清空数组
    exportTableData.splice(0, exportTableData.length);

    for (const item of res.data) {
      exportTableData.push({
        rowId: item._id,
        organizationName: item.name,
        organizationProfile: item.profile,
        organizationMemberCount: 0,
        organizationPrincipal: item.principal,
        organizationCreateTime: formatDate(new Date(item.createTime)),
      });
    }
  }

  exportAllDialogVisible.value = true;
};

const handleCloseExportAllDialog = () => {
  exportAllDialogVisible.value = false;
};

let selectedTable: IObj = reactive({});

const computedSelectedTable = computed(() => {
  const result = [];

  for (const item in selectedTable) {
    if (selectedTable[item].length != 0) {
      result.push(...selectedTable[item]);
    }
  }
  return result;
});
const handleSelectionChange = (selection: IOrganizationTable[]) => {
  selectedTable[pagination.currentPage] = lodash.cloneDeep(selection);
};

const exportSelected = () => {
  if (computedSelectedTable.value.length <= 0) {
    return;
  }

  exportTableData.splice(0, exportTableData.length);

  for (const row of computedSelectedTable.value) {
    exportTableData.push(row);
  }

  exportAllDialogVisible.value = true;
};
</script>

<style lang="less" scoped>
.bottom {
  margin-top: 28px;

  .table-overview {
    display: flex;
    justify-content: space-between;
    height: 60px;
    line-height: 30px;

    .left {
      .total {
        margin-left: 50px;
      }

      .delete-btn {
        margin-left: 20px;
      }
    }
  }
}
</style>
